package com.ifast.sys.controller;


import java.net.URLDecoder;
import java.util.*;

import com.ifast.common.utils.MD5;
import com.ifast.common.utils.PinyinUtil;
import com.ifast.sys.domain.UserDO;
import com.ifast.sys.service.UserService;
import com.ifast.sys.util.PermissUtil;
import com.ifast.sys.util.PrivContent;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.ifast.common.base.AdminBaseController;
import com.ifast.sys.domain.UnitBasicinfoDO;
import com.ifast.sys.service.UnitBasicinfoService;
import com.ifast.common.utils.Result;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 
 * <pre>
 * 学校表
 * </pre>
 * <small> 2018-07-23 12:40:29 | com.wondersgroup</small>
 */
@Controller
@RequestMapping("/sys/unitBasicinfo")
public class UnitBasicinfoController extends AdminBaseController {

	@Autowired
	private UnitBasicinfoService unitBasicinfoService;

	@Autowired
	UserService sysUserService;
	
	@GetMapping()
	@RequiresPermissions("sys:unitBasicinfo:unitBasicinfo")
	String UnitBasicinfo(Model model){
		Map resultMap = getSsqxMapByUserPriv();
		model.addAttribute("ssqxMap", resultMap.get("ssqxMap"));
		return "sys/unitBasicinfo/unitBasicinfo";
	}
	
	@ResponseBody
	@GetMapping("/list")
	@RequiresPermissions("sys:unitBasicinfo:unitBasicinfo")
	public Result<Page<UnitBasicinfoDO>> list(HttpServletRequest request){
		String ssqx = request.getParameter("ssqx");
		String xxlx = request.getParameter("xxlx");
		String xxlb = request.getParameter("xxlb");
		String searchName = request.getParameter("searchName");

        Wrapper<UnitBasicinfoDO> wrapper = new EntityWrapper<UnitBasicinfoDO>();
		wrapper.and("1=1");
		if(StringUtils.isNotBlank(ssqx)){//区县不空
			wrapper.eq("ssqx",ssqx);
		}

		if(StringUtils.isNotBlank(xxlx)){//类型
			wrapper.eq("xxlx",xxlx);
		}

		if(StringUtils.isNotBlank(xxlb)){//类别
			wrapper.eq("xxlb",xxlb);
		}

        if(StringUtils.isNotBlank(searchName)){
			wrapper.like("concat(xxmc,xxsbm)",searchName);//多字段模糊匹配
		}

		/***校验用户范围权限****/
		if(PermissUtil.hasPermission(PrivContent.SM_SJPRIV)) {//市级
			//do nothing
		}else if(PermissUtil.hasPermission(PrivContent.SM_QJPRIV)) {//区级
			wrapper.eq("ssqx",getUser().getUnit().getSsqx());
		}else if(PermissUtil.hasPermission(PrivContent.SM_XJPRIV)){//校级
			wrapper.eq("id",getUser().getUnitid());
		}else{
			wrapper.eq("id",0);
		}

		String sortName = request.getParameter("sortName");
		String sortOrder = request.getParameter("sortOrder");
		if(StringUtils.isNotBlank(sortName)){
			if("ssqxView".equals(sortName)){
				wrapper.orderBy("ssqx","asc".equals(sortOrder));
			}else if("xxlxView".equals(sortName)){
				wrapper.orderBy("xxlx","asc".equals(sortOrder));
			}else if("xxlbView".equals(sortName)){
				wrapper.orderBy("xxlb","asc".equals(sortOrder));
			}else{
				wrapper.orderBy(sortName,"asc".equals(sortOrder));
			}
		}

        Page<UnitBasicinfoDO> page = unitBasicinfoService.selectPage(getPage(UnitBasicinfoDO.class), wrapper);
        return Result.ok(page);
	}
	
	@GetMapping("/add")
	@RequiresPermissions("sys:unitBasicinfo:add")
	String add(Model model){
		model.addAttribute("pageType", "save");
		model.addAttribute("unitBasicinfo",new UnitBasicinfoDO());
		Map resultMap = getSsqxMapByUserPriv();
		model.addAttribute("ssqxMap", resultMap.get("ssqxMap"));
	    return "sys/unitBasicinfo/edit";
	}

	@GetMapping("/look/{id}")
	@RequiresPermissions("sys:unitBasicinfo:unitBasicinfo")
	String look(@PathVariable("id") Long id,Model model){
		model.addAttribute("pageType", "look");
		UnitBasicinfoDO unitBasicinfo = unitBasicinfoService.selectById(id);
		model.addAttribute("unitBasicinfo", unitBasicinfo);
		Map resultMap = getSsqxMapByUserPriv();
		model.addAttribute("ssqxMap", resultMap.get("ssqxMap"));
		return "sys/unitBasicinfo/edit";
	}

	@GetMapping("/edit/{id}")
	@RequiresPermissions("sys:unitBasicinfo:edit")
	String edit(@PathVariable("id") Long id,Model model){
		model.addAttribute("pageType", "update");
		UnitBasicinfoDO unitBasicinfo = unitBasicinfoService.selectById(id);
		model.addAttribute("unitBasicinfo", unitBasicinfo);
		Map resultMap = getSsqxMapByUserPriv();
		model.addAttribute("ssqxMap", resultMap.get("ssqxMap"));
	    return "sys/unitBasicinfo/edit";
	}
	
	/**
	 * 保存
	 */
	@ResponseBody
	@PostMapping("/save")
	@RequiresPermissions("sys:unitBasicinfo:add")
	public Result<String> save( UnitBasicinfoDO unitBasicinfo){
		int num =0;

		Wrapper<UnitBasicinfoDO> wrapper = new EntityWrapper();
		wrapper.where("xxmc={0}",unitBasicinfo.getXxmc());
		num = unitBasicinfoService.selectCount(wrapper);
		if(num>0)return Result.build(Result.CODE_FAIL,"名称已存在");

		wrapper = new EntityWrapper();
		wrapper.where("xxsbm={0}",unitBasicinfo.getXxsbm());
		num = unitBasicinfoService.selectCount(wrapper);
		if(num>0)return Result.build(Result.CODE_FAIL,"学校识别码已存在");


		unitBasicinfo.setCreatetime(new Date());
		unitBasicinfo.setUpdatetime(new Date());
		unitBasicinfo.setOptperson(getUserId());
		unitBasicinfoService.insert(unitBasicinfo);

		wrapper = new EntityWrapper();
		wrapper.where("xxsbm={0}",unitBasicinfo.getXxsbm());
		UserDO user = new UserDO();
		user.setUsername(unitBasicinfo.getXxsbm());//帐号
		user.setPassword(MD5.MD5Encode("123456"));//密码
		user.setName(unitBasicinfo.getXxmc());//名称
		user.setUnitid(unitBasicinfoService.selectOne(wrapper).getId());//单位id
		user.setStatus("1");//用户状态
		user.setUsertype("20");//学校或机构
		user.setCreatetime(unitBasicinfo.getCreatetime());//创建时间
		user.setUpdatetime(unitBasicinfo.getUpdatetime());//更新时间
		user.setOptperson(getUserId());//操作人
		sysUserService.insert(user);
        return Result.ok();
	}
	/**
	 * 修改
	 */
	@ResponseBody
	@RequestMapping("/update")
	@RequiresPermissions("sys:unitBasicinfo:edit")
	public Result<String>  update( UnitBasicinfoDO unitBasicinfo){
		UnitBasicinfoDO old = unitBasicinfoService.selectById(unitBasicinfo.getId());
		if(!old.getXxmc().equals(unitBasicinfo.getXxmc())){
			int num =0;
			Wrapper<UnitBasicinfoDO> wrapper = new EntityWrapper();
			wrapper.where("xxmc={0}",unitBasicinfo.getXxmc());
			num = unitBasicinfoService.selectCount(wrapper);
			if(num>0)return Result.build(Result.CODE_FAIL,"名称已存在");
		}
		unitBasicinfo.setUpdatetime(new Date());
		unitBasicinfo.setOptperson(getUserId());
		unitBasicinfoService.updateById(unitBasicinfo);
		return Result.ok();
	}


	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/getSchoolSbmAuto")
	public void getSchoolSbmAuto(HttpServletRequest request, HttpServletResponse response) {
		StringBuffer sb = new StringBuffer();
		try {
			String scholSbm = "";
			int num =0;
			do {
				scholSbm = "2133" + String.valueOf((int) ((Math.random() * 9 + 1) * 100000));// 随机生成标识码3302+八位随机
				Wrapper<UnitBasicinfoDO> wrapper = new EntityWrapper();
				wrapper.where("xxsbm={0}",scholSbm);
				num = unitBasicinfoService.selectCount(wrapper);
			} while (num>0);
			// 拼装返回值
			sb.append("{\"schoolBsm\":\"");
			sb.append(scholSbm);
			sb.append("\"}");
		} catch (Exception e) {
			sb.delete(0, sb.length());
			sb.append("{\"schoolBsm\":\"\"}");
		} finally {
			sendJson(response, sb);
		}
	}

	// 获取学校名称首字母
	@RequestMapping(value = "/getSchoolMzSzm")
	public void getSchoolMzSzm(HttpServletRequest request,HttpServletResponse response) {
		StringBuffer sb = new StringBuffer();
		try {
			String scholXxmc = request.getParameter("schoolName");
			if (StringUtils.isNotBlank(scholXxmc)) {
				scholXxmc = PinyinUtil.getFirstSpell(scholXxmc).toUpperCase();
			}else{
				scholXxmc="";
			}
			// 拼装返回值
			sb.append("{\"schoolPyMc\":\"");
			sb.append(scholXxmc);
			sb.append("\"}");
		} catch (Exception e) {
			sb.delete(0, sb.length());
			sb.append("{\"schoolPyMc\":\"\"}");
		} finally {
			sendJson(response, sb);
		}
	}

	@RequestMapping(value = "/getSchoolListJson")
	public void getSchoolListJson(HttpServletRequest request, HttpServletResponse response) {
		StringBuffer sb = new StringBuffer();
		boolean b = false;
		try {
			String query = request.getParameter("ssqx");
			Map param = new HashMap();
			if (StringUtils.isNotBlank(query)) {
				param.put("ssqx", query);
			}
			param.put("flag", "1");// 查询启用状态学校
			List<UnitBasicinfoDO> schList = unitBasicinfoService.selectSchJustIdBsmAndName(param);
			sb.append("{\"flag\":\"true\",\"aaData\":[");
			for (UnitBasicinfoDO sch : schList) {
				sb.append("{\"ID\":\"");
				sb.append(sch.getId());
				sb.append("\",\"NAME\":\"");
				sb.append(sch.getXxmc());
				sb.append("\"},");
				b = true;
			}
			if (b)
				sb.deleteCharAt(sb.length() - 1);
			sb.append("]}");
		} catch (Exception e) {
			sb.delete(0, sb.length());
			sb.append("{\"flag\":\"false\",\"msg\":\"\"}");
		} finally {
			sendJson(response, sb);
		}
	}


	@RequestMapping(value = "/getSchoolAutoComplete")
	public void getUnitAutoComplete(HttpServletRequest request, HttpServletResponse response) {
		StringBuffer sb = new StringBuffer();
		try {
			// 当前输入值
			String query = request.getParameter("query");
			query = URLDecoder.decode(query, "utf-8");
			String queryTxt = query.toUpperCase();
			String curssqx = request.getParameter("curssqx");
			String ssqx = request.getParameter("ssqx");
			Map params = new HashMap();
			if (StringUtils.isNotBlank(queryTxt)) {
				params.put("query", queryTxt);
			}
			if (StringUtils.isNotBlank(ssqx)) {
				params.put("ssqx", ssqx);
			}
			if (StringUtils.isNotBlank(curssqx)) {
				params.put("ssqx", getUser().getUnit().getSsqx());
			}
			params.put("flag", "1");// 查询启用状态学校
			List<UnitBasicinfoDO> schList = unitBasicinfoService.selectSchJustIdBsmAndName(params);
			// 拼装返回值
			sb.append("{\"query\":\"");
			sb.append(query);
			sb.append("\",\"suggestions\":[");
			if (!schList.isEmpty()) {
				for (UnitBasicinfoDO vo : schList) {
					String value = vo.getXxmc();
					Long data = vo.getId();
					String xxjc = vo.getXxpyjc();
					if (StringUtils.isNotBlank(value)) {
						sb.append("{\"data\":\"");
						sb.append(data);
						sb.append("\",\"value\":\"");
						sb.append(value);
						sb.append("\",\"xxjc\":\"");
						sb.append(xxjc);
						sb.append("\"},");
					}
				}
				sb.deleteCharAt(sb.length() - 1);
			}
			sb.append("]}");
		} catch (Exception e) {
			sb.delete(0, sb.length());
			sb.append("{\"query\":\"key\",\"suggestions\":[]}");
		} finally {
			sendJson(response, sb);
		}
	}

}
